import pandas as pd
import datetime

#
asset_class = ["股票", "债券", "货币", "海外", "商品"]
strategy_class = ["股票多头", "债券", "货币", "CTA", "中性", "混合策略"]


#
def Code_Suffix(symbol):
    x = symbol.split(".")
    return x[0], x[1]


def Fund_Asset_Class(x):
    invest_type1 = x["invest_type1"]
    invest_type2 = x["invest_type2"]
    if invest_type1 == "混合型基金" or invest_type1 == "股票型基金":
        return "股票"
    if invest_type1 == "债券型基金":
        return "债券"
    if invest_type1 == "货币市场型基金":
        return "货币"
    if invest_type1 == "国际(QDII)基金":
        return "海外"
    if invest_type2 == "商品型基金":
        return "商品"
    else:
        return "股票"


def Convert_MutualFund(database, datetime2):
    # 处理公募基金
    df_mutualfund = database.Get_Instruments_DataFrame(instrument_type="mutualfund")
    df_mutualfund = df_mutualfund[
        ["key2", "symbol", "description", "invest_type1", "invest_type2", "datetime1", "datetime2"]]

    df_mutualfund["instrument_type"] = "MutualFund"
    df_mutualfund["country"] = "CN"
    df_mutualfund["currency"] = "CNY"
    df_mutualfund["date"] = datetime2
    df_mutualfund["datetime"] = datetime2
    #
    df_mutualfund["code"] = df_mutualfund["symbol"].apply(lambda x: Code_Suffix(x)[0])
    df_mutualfund["suffix"] = df_mutualfund["symbol"].apply(lambda x: Code_Suffix(x)[1])
    df_mutualfund["start_date"] = df_mutualfund["datetime1"].apply(lambda x: x.date())
    df_mutualfund["end_date"] = df_mutualfund["datetime2"].apply(lambda x: x.date())
    #
    df_mutualfund["asset_type"] = df_mutualfund.apply(lambda x: Fund_Asset_Class(x), axis=1)
    df_mutualfund["daily_quote_table"] = "mutualfund_dailybar"
    df_mutualfund["instrument_table"] = "instrument_mutualfund"
    #
    database.SaveDataFrame("financial_data", "instrument", df_mutualfund)


def Convert_Index(database, datetime2):
    def Process_Index_Country(x):
        currency = x["currency"]
        if currency == "CNY":
            return "CN"
        if currency == "HKD":
            return "HK"
        if currency == "USD":
            return "US"
        else:
            return None

    def Process_Index_Asset_Class(x):
        desc = x["description"]
        country = x["country"]
        if "债" in desc:
            return "债券"
        if country in ["HK", "US"]:
            return "海外"
        else:
            return "股票"

    df_index = database.Get_Instruments_DataFrame(instrument_type="Index")
    df_index = df_index[
        ["key2", "symbol", "description", "exchange", "currency", "datetime1", "datetime2"]]
    #
    df_index["instrument_type"] = "Index"
    df_index["date"] = datetime2
    df_index["datetime"] = datetime2
    #
    df_index["code"] = df_index["symbol"].apply(lambda x: Code_Suffix(x)[0])
    df_index["suffix"] = df_index["symbol"].apply(lambda x: Code_Suffix(x)[1])
    df_index["start_date"] = df_index["datetime1"].apply(lambda x: x.date())
    df_index["end_date"] = df_index["datetime2"].apply(lambda x: x.date())

    df_index["country"] = df_index.apply(lambda x: Process_Index_Country(x), axis=1)
    #
    df_index["asset_type"] = df_index.apply(lambda x: Process_Index_Asset_Class(x), axis=1)
    df_index["daily_quote_table"] = "index_dailybar"
    df_index["instrument_table"] = "instrument_index"
    #
    database.SaveDataFrame("financial_data", "instrument", df_index)


def Convert_Stock(database, datetime2):
    df_mutualfund = database.Get_Instruments_DataFrame(instrument_type="stock")
    df_mutualfund = df_mutualfund[
        ["key2", "symbol", "description", "exchange", "market", "industry", "datetime1", "datetime2"]]

    df_mutualfund["instrument_type"] = "Stock"
    df_mutualfund["country"] = "CN"
    df_mutualfund["currency"] = "CNY"
    df_mutualfund["asset_type"] = "股票"
    df_mutualfund["date"] = datetime2
    df_mutualfund["datetime"] = datetime2
    #
    df_mutualfund["code"] = df_mutualfund["symbol"].apply(lambda x: Code_Suffix(x)[0])
    df_mutualfund["suffix"] = df_mutualfund["symbol"].apply(lambda x: Code_Suffix(x)[1])
    df_mutualfund["start_date"] = df_mutualfund["datetime1"].apply(lambda x: x.date())
    df_mutualfund["end_date"] = df_mutualfund["datetime2"].apply(lambda x: x.date())
    #
    df_mutualfund["daily_quote_table"] = "stock_dailybar"
    df_mutualfund["instrument_table"] = "instrument_stock"
    #
    database.SaveDataFrame("financial_data", "instrument", df_mutualfund)


def Convert_FutureIndex(database, datetime2):
    #
    def Process_FutureIndex_Asset_Class(x):
        exchange = x["exchange"]
        code = x["code"]
        if code in ["IF", "IC", "IH"]:
            return "股票"
        if code in ["T", "TF", "TS"]:
            return "债券"
        else:
            return "商品"
    #
    df_mutualfund = database.Get_Instruments_DataFrame(instrument_type="futureindex")
    df_mutualfund = df_mutualfund[
        ["symbol", "description", "exchange", "datetime1", "datetime2"]]

    df_mutualfund["key2"] = df_mutualfund["symbol"]
    df_mutualfund["instrument_type"] = "FutureIndex"
    df_mutualfund["country"] = "CN"
    df_mutualfund["currency"] = "CNY"
    df_mutualfund["date"] = datetime2
    df_mutualfund["datetime"] = datetime2
    #
    df_mutualfund["code"] = df_mutualfund["symbol"].apply(lambda x: Code_Suffix(x)[0])
    df_mutualfund["suffix"] = df_mutualfund["symbol"].apply(lambda x: Code_Suffix(x)[1])
    df_mutualfund["start_date"] = df_mutualfund["datetime1"].apply(lambda x: x.date())
    df_mutualfund["end_date"] = df_mutualfund["datetime2"].apply(lambda x: x.date())
    #
    df_mutualfund["asset_type"] = df_mutualfund.apply(lambda x: Process_FutureIndex_Asset_Class(x), axis=1)
    df_mutualfund["daily_quote_table"] = "future_dailybar"
    df_mutualfund["instrument_table"] = "instrument_future"
    #
    database.SaveDataFrame("financial_data", "instrument", df_mutualfund)


def Build_Standard_Instruments(database, datetime2):
    #
    Convert_MutualFund(database, datetime2)
    Convert_Index(database, datetime2)
    Convert_Stock(database, datetime2)
    Convert_FutureIndex(database, datetime2)


if __name__ == '__main__':
    #
    # ---Connect to DataBase, Find Series 连接数据库---
    from Core.Config import *
    pathfilename = os.getcwd() + "\..\Config\config2.json"
    config = Config(pathfilename)
    database = config.DataBase("JDMySQL")
    realtime = config.RealTime()

    Build_Standard_Instruments(database, datetime.datetime(2020,9,15))